package com.scut.dispatching_server.service;

import com.scut.dispatching_server.config.GlobalVariables;
import com.scut.dispatching_server.model.Demand;
import com.scut.dispatching_server.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class DemandCache {
    @Autowired
    private RedisUtil redisUtil;

    public boolean saveToCache(Demand demand) {
        Map<String, Object> demandMap = new HashMap<>();
        demandMap.put("lon", demand.getLon());
        demandMap.put("lat", demand.getLat());
        demandMap.put("time", demand.getTime());
        redisUtil.hmset(demand.getId(), demandMap, GlobalVariables.REAL_TIME_LENGTH);
        return true;
    }

    public ArrayList<String> getCachedDemands() {
        ArrayList<String> demandIds = new ArrayList<>();
        Set<Object> demandsSet = redisUtil.sGet(GlobalVariables.ALIVE_DEMAND_SET_KEY);
        for (Object demandId : demandsSet) {
            demandIds.add((String)demandId);
        }
        return demandIds;
    }

    public long addAliveDemand(String id) {
        return redisUtil.sSet(GlobalVariables.ALIVE_DEMAND_SET_KEY, id);
    }

    public Demand getDemand(String id) {
        Map<Object, Object>  rawDemand =  redisUtil.hmget(id);
        return new Demand(id, (float)rawDemand.get("lon"), (float)rawDemand.get("lat"), (LocalDateTime)rawDemand.get("time"));
    }

    public boolean deleteDemand(String id) {
        if (redisUtil.setRemove(GlobalVariables.ALIVE_DEMAND_SET_KEY, id) > 0){
            return true;
        }
        return false;
    }
}
